package com.example.tarea2;

import java.util.Date;
import java.util.Random;








import android.view.LayoutInflater;
import android.view.View;

import android.content.Context;

import android.util.AttributeSet;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ControlCap extends LinearLayout {
	
	private int resultado;
	private TextView captcha;
	private TextView error;
	private EditText nombre;
	private EditText resUser;
	private Button login;
	private boolean acceso;
	private onCaptchaListener oncaptchalistener;
	

	public ControlCap(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	
		inicializar();
	}

	public ControlCap(Context context, AttributeSet attrs) {
		super(context, attrs);
		inicializar();
	}

	public ControlCap(Context context) {
		super(context);
		inicializar();
	}

	public void inicializar(){
		String infService = Context.LAYOUT_INFLATER_SERVICE;
		LayoutInflater li=(LayoutInflater)getContext().getSystemService(infService);
		li.inflate(R.layout.controlcap, this, true);    
		captcha= (TextView) findViewById(R.id.textView3);
		error= (TextView) findViewById(R.id.textVError);
		login=(Button)findViewById(R.id.button1234);
		nombre=(EditText)findViewById(R.id.editNombre);
		resUser=(EditText)findViewById(R.id.editRes);
		acceso=false;
		String[] operadores = {"+","*"};
		Date sec=new Date();
		final Random myRandom = new Random(sec.getSeconds());
		
		
		int x=myRandom.nextInt(20);
		int y=myRandom.nextInt(20);
		int op=myRandom.nextInt(2);		
		String montada=x+operadores[op]+y+"=";
		captcha.setText(montada);
		calcularRes(x,y,op);
		asignarEventos();
		
	}
	
	private void calcularRes(int x, int y, int op){
		
		switch(op){
		
		case 0:
			resultado= x+y;
			break;
		case 1:
			resultado=x*y;
			break;
		
		
		}
		
		
	}
	
	private void asignarEventos(){
		
		login.setOnClickListener(new OnClickListener()
	    {      
	      

			@Override
			public void onClick(View arg0) {
				setError("");
				int aux=0;
				int comp=0;
				String err="";
				if(nombre.getText().length()<=0){
					err+=getError()+" Nombre vacio|";
					comp=-1;
				}
				if(resUser.getText().length()>0)
					aux=Integer.parseInt(resUser.getText().toString());
				if(resultado!=aux){
					err+=getError()+"|Captcha incorrecto";
					comp=-1;
				}
				if(comp!=-1){
					oncaptchalistener.onCaptcha(true);
					
				}else setError(err);
				
				
			}
	    });
		
	}
	
	
	
	public String getNombre(){
		return nombre.getText().toString();
	}
	
	public boolean getAcceso(){
		return acceso;
	}

	

	private void setError(String s){
		error.setText(s);
		
	}
	
	private String getError(){
		
		return error.getText().toString();
	}
	
	public void setCaptchaListener(onCaptchaListener oll){
		oncaptchalistener=oll;
	}
	
	
	

}
